/**
 *
 */
package com.naiterui.ehp.bs.recommend.handler;

import java.util.List;
import java.util.concurrent.DelayQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.naiterui.ehp.bp.utils.thread.ThreadPoolUtil;
import com.naiterui.ehp.bs.recommend.bean.DrMedicationRecomInfo;
import com.naiterui.ehp.bs.recommend.bean.mongo.DrugTask;
import com.naiterui.ehp.bs.recommend.dao.mongo.DrugTaskDao;
import com.naiterui.ehp.bs.recommend.service.IRecomService;

//@Service
public class RecomAuditHandler implements InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(RecomAuditHandler.class);

    private static final int DEFAULT_DELAY_TIME = 5;

    @Autowired
    private DrugTaskDao drugTaskDao;
    @Autowired
    private IRecomService recomService;

    /**
     * 自动审核队列
     */

    private DelayQueue<DrugWrapper> drugQueue = new DelayQueue<>();

    @Override
    public void afterPropertiesSet() {
        this.autoAudit();
        this.initDrugTask();
    }

    public void initDrugTask() {
        List<DrugTask> drugTasks = this.drugTaskDao.findAllDrugTask(DrugTask.UNEXECUTED);
        for (DrugTask drugTask : drugTasks) {
            this.drugQueue.offer(new DrugWrapper(drugTask.getRecommandId(), drugTask.getEndTime()));
        }
        LOGGER.info("initDrugTask complete ;");
    }

    public void waitAudit(Long recomId, Integer delayTime) {

        if (null == delayTime || delayTime <= 0) {
            delayTime = DEFAULT_DELAY_TIME;
        }
        long endTime = System.currentTimeMillis() + delayTime * 1000;
        LOGGER.info("waitAudit endTime:{}", endTime);

        // 持久化队列数据
        DrugTask drugTask = new DrugTask();
        drugTask.setRecommandId(recomId);
        drugTask.setEndTime(endTime);
        drugTask.setStatus(DrugTask.UNEXECUTED);
        this.drugTaskDao.saveDrugTask(drugTask);

        this.drugQueue.put(new DrugWrapper(recomId, endTime));

    }

    private void autoAudit() {

        ThreadPoolUtil.execute(() -> {
            // 循环处理队列中的session
            while (true) {
                try {

                    DrugWrapper drugWrapper = RecomAuditHandler.this.drugQueue.take();

                    // 取出最早的一条记录
                    LOGGER.debug("autoAuditDrug Excecuting");
                    // 随机获取药师 TODO
                    // 审核通过后
                    RecomAuditHandler.this.recomService.saveCrmRecomConfirm(drugWrapper.getRecommandId(), 0L, "", drugWrapper.getEndTime(),
                            DrMedicationRecomInfo.CHECKING_STATUS_PASS, "");
                    RecomAuditHandler.this.drugTaskDao.removeDrugTask(drugWrapper.getRecommandId());

                } catch (Exception e) {
                    LOGGER.error("[推荐自动审核] autoAudit ERROR ；", e);
                }
            }
        });

    }

}
